class MUtil{
    
    request(param){
        return new Promise((resolve, reject) => {
            $.ajax({
                type     : param.type     || 'get',
                url      : param.url      || '',
                dataType : param.dataType || 'json',
                data     : param.data     || null,
                success  : (res) => {
                    //请求成功
                    if(res.status === 0){
                        typeof resolve === 'function' && resolve(res.data, res.msg);
                    }
                    //没有登录状态，强制登陆
                    else if(res.status === 10){
                        this.doLogin();
                    }
                    //请求错误
                    else{
                        typeof reject === 'function' && reject(res.msg  || res.data);
                    }
                },
                error   : (err) => {
                    typeof reject === 'function' && reject(err.statusText);
                }
            });
        });
    }
    //跳转登录
    doLogin(){
        window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname)
    }
    //获取URL参数
    getUrlParam(name){
        //xxxxx.com?param=123&param1=456
        // queryString取到的数据：param=123 &param1=456
        let queryString = window.location.search.split('?')[1] || '',
            reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
            result = queryString.match(reg);
        //result: ['param=123','','123','&']\
        return result ? decodeURIComponent(result[2]) : null;
    }
    //错误提示
    errorTips(errMsg){
        alert(errMsg || '好像哪里不对了~');
    }
    //成功提示
    successTips(successMsg){
        alert(successMsg || '操作成功啦！');
    }
    //存储localStorage数据
    setStorage(name, data){
        let dataType = typeof data
        //JSON类型
        if(dataType === 'object'){
            window.localStorage.setItem(name, JSON.stringify(data))
        }
        //基础类型
        else if(['number', 'string', 'boolean'].indexOf(dataType) >= 0){
            window.localStorage.setItem(name, data);
        }
        //其他类型
        else{
            alert('该类型不能用于本地存储');
        }
    }
    //取出localStorage数据
    getStorage(name){
        let data = window.localStorage.getItem(name);
        if(data){
            return JSON.parse(data)
        }
        else{
            return ''
        }
    }
    //删除localStorage数据
    removeStorage(name){
        window.localStorage.removeItem(name);
    }
}

export default MUtil;